import { setTheme } from '@fe/services/theme'
import * as storage from '@fe/utils/storage'
import { FLAG_DEMO } from '@fe/support/args'
import { useToast } from '@fe/support/ui/toast'
import { t } from '@fe/services/i18n'

let settings = {
  repositories: { test: '/path_test' },
  shell: 'bash'
}

if (FLAG_DEMO) {
  storage.clear()
  setTheme('dark')

  const xFetch = window.fetch
  const xOpen = window.open
  const cache: {[key: string]: string} = {}

  window.addEventListener('error', e => {
    const target = e.target as HTMLImageElement
    if (target.tagName === 'IMG') {
      if (target.src.includes('/api/plantuml')) {
        target.src = ''
      } else if (target.src.includes('/api/help')) {
        const url = new URL(target.src)
        const path = url.searchParams.get('path')
        if (path) {
          target.src = path.replace(/^.\//, '/')
        }
      }
    } else {
      console.error(e)
    }
  }, true)

  const fakeFetch = (uri: any, init: any) => Promise.resolve({
    json: () => {
      console.log('mock api >', uri, init)

      const url = new URL(location.origin + uri)
      const method = (init && init.method) || 'GET'

      if (uri.startsWith('/api/settings')) {
        if (method === 'POST') {
          settings = JSON.parse(init.body)
        }

        return Promise.resolve({
          status: 'ok',
          message: 'success',
          data: JSON.parse(JSON.stringify(settings))
        })
      }

      if (uri.startsWith('/api/mark')) {
        return Promise.resolve({ status: 'ok', message: 'success', data: {} })
      }

      if (uri.startsWith('/api/repositories')) {
        return Promise.resolve({ status: 'ok', message: 'success', data: { test: '/test' } })
      }

      if (uri.startsWith('/api/tree')) {
        return Promise.resolve({ status: 'ok', message: 'success', data: [{ name: '/', type: 'dir', path: '/', repo: 'test', children: [{ name: 'Work', path: '/Work', type: 'dir', repo: 'test', children: [{ name: '1.md', path: '/Work/1.md', type: 'file', repo: 'test', marked: false, birthtime: 1623635402958.447, mtime: 1623635402958.447 }, { name: '2.md', path: '/Work/2.md', type: 'file', repo: 'test', marked: false, birthtime: 1623635406528.4639, mtime: 1623635406528.4639 }, { name: '3.md', path: '/Work/3.md', type: 'file', repo: 'test', marked: false, birthtime: 1623635410176.051, mtime: 1623635410177.0498 }] }, { name: 'Learn', path: '/Learn', type: 'dir', repo: 'test', children: [{ name: 'a.md', path: '/Learn/a.md', type: 'file', repo: 'test', marked: false, birthtime: 1623635423871.2678, mtime: 1623635423871.2678 }, { name: 'b.md', path: '/Learn/b.md', type: 'file', repo: 'test', marked: false, birthtime: 1623635427472.3079, mtime: 1623635427472.3079 }, { name: 'c.md', path: '/Learn/c.md', type: 'file', repo: 'test', marked: false, birthtime: 1623635431935.041, mtime: 1623635431935.041 }] }, { name: 'TEST.md', path: '/TEST.md', type: 'file', repo: 'test', marked: false, birthtime: 1623635389096.3315, mtime: 1623635389097.3403 }, { name: 'TODO.md', path: '/TODO.md', type: 'file', repo: 'test', marked: false, birthtime: 1623635437968.1262, mtime: 1623635437969.1235 }, { name: 'Secret.c.md', path: '/Secret.c.md', type: 'file', repo: 'test', marked: false, birthtime: 1623635542753.2976, mtime: 1623635542753.2976 }, { name: 'Project.luckysheet', path: '/Project.luckysheet', type: 'file', repo: 'test', marked: false, birthtime: 1623635542753.2976, mtime: 1623635542753.2976 }] }] })
      }

      if (uri.startsWith('/api/help') || uri.startsWith('/api/file')) {
        if (method === 'POST') {
          return Promise.resolve({ status: 'ok', message: 'success' })
        } else if (method === 'GET') {
          if ((url.searchParams.get('path') || '').endsWith('.luckysheet')) {
            const content = JSON.stringify([{
              name: 'Sheet1',
              color: '',
              status: 1,
              order: 0,
              data: Array(20).fill(Array(14).fill(null)),
              config: {
                merge: {},
                rowlen: {},
                rowhidden: {}
              },
              index: 0,
              jfgird_select_save: [],
              luckysheet_select_save: [{
                row: [0, 0],
                column: [0, 0],
                row_focus: 0,
                column_focus: 0,
                left: 0,
                width: 73,
                top: 0,
                height: 19,
                left_move: 0,
                width_move: 73,
                top_move: 0,
                height_move: 19
              }],
              visibledatarow: [],
              visibledatacolumn: [],
              ch_width: 4560,
              rh_height: 1760,
              luckysheet_selection_range: [],
              zoomRatio: 1,
              scrollLeft: 0,
              scrollTop: 0,
              calcChain: [],
              filter_select: null,
              filter: null,
              luckysheet_conditionformat_save: [],
              luckysheet_alternateformat_save: [],
              dataVerification: {},
              hyperlink: {},
              celldata: []
            }])
            return Promise.resolve({
              status: 'ok',
              message: 'success',
              data: { content, hash: 'test' }
            })
          }

          const path = '/' + (url.searchParams.get('doc')?.replace(/^\//, '') || 'FEATURES.md')
          const data = {
            status: 'ok',
            message: 'success',
            data: {
              content: '',
              hash: 'test'
            }
          }

          const replaceContnet = (str: string) => {
            const message = (url.searchParams.get('doc') ? '' : (t('demo-tips') + '{style="color: red; font-size: 30px"}\n\n'))

            const idx = str.indexOf('#')
            return str.substring(0, idx) + message + str.substring(idx)
          }

          if (cache[path]) {
            data.data.content = replaceContnet(cache[path])
            return Promise.resolve(data)
          }

          return xFetch(path).then(res => res.text()).then(md => {
            md = md.replace(/```markdown\n(\[luckysheet\].+)\n```/, '$1')
            cache[path] = md
            data.data.content = replaceContnet(md)
            return data
          })
        }
      }

      const message = t('demo-tips')
      useToast().show('warning', message)

      return Promise.resolve({ status: 'error', message })
    }
  } as any)

  window.fetch = (uri: any, init: any) => {
    if (uri.startsWith('https://') || uri.startsWith('http://')) {
      return xFetch(uri, init)
    }

    return fakeFetch(uri, init)
  }

  window.open = function (...args: any[]) {
    const win = xOpen(...args)
    win!.fetch = window.fetch
    return win
  }
}
